package com.scut.fy.auth.config;

import com.scut.fy.common.core.constant.FyConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


/**
 * @author jy
 */
@Configuration
@EnableAuthorizationServer
public class FyAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private static final Logger log = LoggerFactory.getLogger(FyAuthorizationServerConfig.class);

    @Lazy
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private DataSource dataSource;

    @Resource
    private UserDetailsService userDetailsService;

    @Resource
    private FyOauth2ClientProperties fyOauth2ClientProperties;
    @Resource
    private RedisConnectionFactory redisConnectionFactory;

    /**
     * 用来配置客户端详情服务（ClientDetailsService），客户端详情信息在这里进行初始化，
     * 你能够把客户端详情信息写死在这里或者是通过数据库来存储调取详情信息
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
        log.info("ClientsDetailAuthenticationManager......................." + authenticationManager);
        /**
         * 1. 使用JdbcClientDetailsService客户端详情服务
         */
//        clients.withClientDetails(new JdbcClientDetailsService(dataSource));

        /**
         * 2. 逐个属性配置,inMemory是存储到内存中 并未到数据库
         */
        clients.inMemory()
                .withClient(fyOauth2ClientProperties.getClientId())
                .secret(fyOauth2ClientProperties.getClientSecret())
                .scopes(fyOauth2ClientProperties.getScope())
                .refreshTokenValiditySeconds(60*30);

    }

    /**
     * 用来配置授权（authorization）以及令牌（token）的访问端点和令牌服务(token services)
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        log.info("EndpointsAuthenticationManager......................." + authenticationManager);
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(jwtAccessTokenConverter()));

        endpoints.authenticationManager(authenticationManager)
                // token存储在redis
                .tokenStore(redisTokenStore())
                // 配置token的属性
                .tokenEnhancer(tokenEnhancerChain)
                // 配置JwtAccessToken转换器
                .accessTokenConverter(jwtAccessTokenConverter())
                // refresh_token需要userDetailsService
                .reuseRefreshTokens(false).userDetailsService(userDetailsService);
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(endpoints.getTokenStore());
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setClientDetailsService(endpoints.getClientDetailsService());
        tokenServices.setTokenEnhancer(endpoints.getTokenEnhancer());
        // access_token有效时长30分钟
        tokenServices.setAccessTokenValiditySeconds(30*60);
        // refresh_token有效时长12小时
        tokenServices.setRefreshTokenValiditySeconds(12*60*60);
        endpoints.tokenServices(tokenServices);
    }


    /**
     * 用来配置令牌端点(Token Endpoint)的安全约束
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(final AuthorizationServerSecurityConfigurer security) throws Exception {
        log.info("SecurityAuthenticationManager......................." + authenticationManager);
        security.allowFormAuthenticationForClients()
                .tokenKeyAccess("isAuthenticated()")
                .checkTokenAccess("permitAll()");
    }

    /**
     * 使用redis存储token
     * @return
     */
    @Bean
    public TokenStore redisTokenStore() {
        RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory);
        tokenStore.setPrefix("com.scut.fy.token");
        return tokenStore;
    }

    /**
     * 配置jwt的加密方式
     * @return
     */
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        final JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter(){
            @Override
            public OAuth2AccessToken enhance (OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
                String userName = authentication.getUserAuthentication().getName();
                // 与登录时候放进去的UserDetail实现类一直查看link{SecurityConfiguration}
                User user = (User) authentication.getUserAuthentication().getPrincipal();
                /** 自定义一些token属性 ***/
                final Map<String, Object> additionalInformation = new HashMap<>();
                additionalInformation.put("userName", userName);
                additionalInformation.put("userRoles", user.getAuthorities());
                ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInformation);
                OAuth2AccessToken enhancedToken = super.enhance(accessToken, authentication);
                return enhancedToken;
            }
        };
        // 对称加密，表示认证服务端和认证客户端的共用一个key
        jwtAccessTokenConverter.setSigningKey(FyConstant.SIGN_KEY);
        return jwtAccessTokenConverter;
    }

    /**
     * 生成token 定制化处理
     * @return TokenEnhancer
     */
//    @Bean
//    private TokenEnhancer tokenEnhancer() {
//        return (accessToken, authentication) -> {
//            //设置token的过期时间30分钟
//            Calendar nowTime = Calendar.getInstance();
//            nowTime.add(Calendar.MINUTE, 30);
//            ((DefaultOAuth2AccessToken) accessToken).setExpiration(nowTime.getTime());
//            return accessToken;
//        };
//    }

}
